<template>
  <div>
  <el-table :data="filterTableData"  border style="width: 100%" :key="updateKey">
    <el-table-column label="提交日期" prop="date" />
    <el-table-column label="论文题目" prop="name" />
    <el-table-column
        prop="state"
        label="审核状态"
        width="100"
        column-key="state"
        :filters="[{ text: '审核中', value: '审核中' }, { text: '已通过', value: '已通过' }]"
        :filter-method="filterStatus"
    >
      <template #default="scope">
        <el-tag
            :type="scope.row.state === '审核中' ? 'primary' : 'success'"
            disable-transitions>{{scope.row.state}}</el-tag>
      </template>
    </el-table-column>


    <el-table-column label="分数" prop="score" />
    <el-table-column align="right">
      <template #header style="text-align: center">
        <el-input v-model="input" size="small" placeholder="输入文章题目/作者" style="width: 80%;justify-content: start"/>
        <el-button size="small"  type="primary" @click="searchFind" style="width: 20%;justify-content: end">搜索</el-button>
      </template>
      <template #default="scope" >

        <!--修改论文-->
        <el-button  size="small" @click="dialogFormVisible = true; setFocus(scope.row)" type="primary" style="margin-right: 13px">修改</el-button>

        <!--查看-->

        <el-button size="small" @click=" setFocus(scope.row); go();" type="info" >查看</el-button>
        <!--下载-->
        <el-button size="small" @click="download(scope.row)" type="success">下载</el-button>
        <!--删除-->
<!--        <el-button v-show="false"-->
<!--            size="small"-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.$index, scope.row)">删除</el-button>-->

      </template>
    </el-table-column>

  </el-table>

  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totalPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</div>
  <!--修改弹窗-->
  <el-dialog v-model="dialogFormVisible" title="论文修改">
    <el-form :model="form">
      <el-form-item label="论文题目" :label-width="formLabelWidth" >
        <el-input v-model="form.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="提交论文" :label-width="formLabelWidth">
        <el-upload
            id="file"
            ref="upload"
            class="upload-demo"
            action="#"
            :limit="1"
            :on-exceed="handleExceed"
            :auto-upload="false"
            @change="updateFile"
        >
          <template #trigger>
            <el-button type="primary">选择上传的文件</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip text-red">
              只能上传一个文件，新的文件会被覆盖
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-form-item label="论文描述" :label-width="formLabelWidth">
        <el-input  type="textarea"  v-model="form.reason"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false; ">取消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false; onSubmit(this)">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, computed, ref, toRaw, inject} from 'vue'
import {ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile, ElTable} from "element-plus";
import axios, {Axios} from "axios";
import assert from "assert";
const reload = inject('reload')

interface Paper {
  id: number
  date: string
  name: string
  state:string
  score:string
}
const dialogFormVisible = ref(false)
let selectedID = ref(0)
const input = ref()
const formLabelWidth = '140px'
const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const searchFind = ()=>{
  if(input.value===""){
    set();
    return;
  }
  axios.get(`/paper/search?content=${input.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res=>{
    if(res.data.code===0)
    {
      while (tableData.length != 0) tableData.pop();
      console.log(tableData);
      res.data.data.list.forEach(function (e) {

        let user: Paper = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.title,
          // author:e.authorOneName,
          state: e.status===1?"通过":(e.status===0?"审核中":"不通过"),
          score: e.score,
        };
        tableData.push(user);

      })
      console.log(res);
      totalPage.value =res.data.data.total;
      console.log(res.data.data.pageNum);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    }
    else{
      ElMessage('搜索失败');
    }
  })
}
const handleDelete = (index: number, row: Paper) => {
  confirm("该操作不可恢复，是否继续？");
  console.log(index, row)
  let item = toRaw(row)
  axios.get(`paper/delete?paperId=${item.id}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      set();
    } else {
      ElMessage('删除失败');
    }
  })
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}


const tableData = reactive<Paper[]>([

])

let updateKey = ref(1)
let currentPage = ref(1)
let pageSize = ref(5)
let totalPage = ref(0)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)

const set = ()=> {
  axios.get(`paper/list?pageSize=${pageSize.value}&pageNum=${currentPage.value}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      while (tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e) {
        let stateN = e.status =='0' ? '审核中':'已通过';
        let paper: Paper = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.title,
          state: stateN,
          score: e.score
        };
        tableData.push(paper);
      })
      console.log(res);
      totalPage = res.data.data.pages;
      console.log(res.data.data.pageNum);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    } else {
      ElMessage('切换失败');
    }
  })
}
set()



const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  console.log(currentPage);
  axios.get(`paper/list?pageSize=${val}&pageNum=${1}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){
        let stateN = e.status=='0' ? '审核中':'已通过';
        let paper:Paper = {
          id: e.id,
          date: e.uploadTime.split(' ')[0],
          name: e.title,
          state: stateN,
          score:  e.score,
        };
        tableData.push(paper);
      })
      totalPage = res.data.pages;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)

  axios.get(`paper/list?pageSize=${pageSize.value}&pageNum=${val}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
        console.log(tableData);
        if(res.data.code === 0) {
          while(tableData.length != 0) tableData.pop();

          console.log(tableData);
          res.data.data.list.forEach(function (e){
            let stateN = e.status=='0' ? '审核中':'已通过';
            let paper:Paper = {
              id: e.id,
              date: e.uploadTime.split(' ')[0],
              name: e.title,
              state: stateN,
              score: e.score
            };
            tableData.push(paper);
          })
          totalPage = res.data.pages;
          currentPage = res.data.pageNum;
          // updateKey.value += 1;
          console.log(filterTableData);
        }else {
          ElMessage('切换失败');
        }
  })
}

const downloadAttach = (flag: string, title:string) => {
  // 发送get请求
  console.log(flag)
  axios.get(`/paper/download/${flag}`, {
        headers: {
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        },
        responseType: 'blob'
      })
      .then(res => {
        const blob = new Blob([res.data]);//处理文档流
        const disposition = decodeURI(res.headers['content-disposition']);
        let fileName = disposition.substring(disposition.indexOf('fileName=')+9, disposition.length);
        console.log(res.headers['content-disposition']);
        console.log(res);
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      })
      .catch(() => {
        alert("请求出错");
      })
  // alert(url);
}

const download = (row: Paper) => {
  console.log(row)
  let item = toRaw(row);
  console.log(item);
  axios.get(`paper?paperId=${item.id}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    if(res.data.code === 0) {
      console.log(res.data);
      let length = res.data.data.filePath.toString().split('/').length;
      let flag = res.data.data.filePath.toString().split('/')[length-1];
      console.log(flag);

      downloadAttach(flag, item.name)
    }else {
      console.log("获取flag出错")
      ElMessage('下载失败');
    }
  })
}
const setFocus = (row:Paper) => {
  console.log(row);
  selectedID = ref(row.id);
  console.log(selectedID.value);
}
//论文信息部分表格
const form = reactive({
  "authorOneName": "string",
  "authorThreeName": "string",
  "authorTwoName": "string",
  "filePath": "string",
  "title": "",
  "type": "string",
});

var file = reactive({})
const onSubmit = () => {
  let info = form
  let paperID:number = selectedID.value;
  let infoJson = JSON.stringify(form);
  axios.post(`paper/update?paperId=${paperID}`, info, {
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{

    if(res.data.code === 0){
      let param = new FormData();//创建form对象
      console.log("file"+file);
      console.log("paperid"+selectedID);
      if(JSON.stringify(file)==="{}") {
        ElMessage("修改失败，您没有上传文件");
      } else {
        param.append("file", file);//为创建的form对象增加上传的文件
        param.append("paperId", selectedID.value);//如果需要上传其他字段，在这里增加
        if(form.title==="")
        {
          ElMessage('提交失败，请输入论文题目');
          return false;
        }
        let config = { headers: { 'Content-Type': 'multipart/form-data', 'session':localStorage.getItem('ID'),  } }//修改请求头
        let url = "paper/upload";
        console.log(param);
        axios.post(url, param, config).then((res) => {
          console.log(res, "res");
          if(res.data.code === 0) {
            ElMessage("修改成功");
            reload()
          } else {
            ElMessage(res.data.commonErrorCode.errorSuggestion);
          }
        });
      }
    } else {
      ElMessage(res.data.commonErrorCode.errorSuggestion);
    }
  })
}

import { getCurrentInstance } from "vue";
import router from "../router";
import {useRouter} from "vue-router";
const { proxy } = getCurrentInstance();//获取原型
const Axios = proxy.$axios;//Axios就是挂在的原型（相当于vue2中的this.$axios）
const updateFile = (e) => {
  console.log(e);
  file = e.raw;//拿到上传的file
}

const go = () => {
  router.push ({
    path:"/display",
    query:{
      paperId: selectedID.value
    }
  });
}

</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
</style>